package handler

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"zk3.12/api/request"
	"zk3.12/glodal"
	"zk3.12/internal/model"
)

func LiveAdd(c *gin.Context) {
	var req request.LiveAdd
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}

	live := model.Live{
		Model:      gorm.Model{},
		LiveId:     req.LiveId,
		UserId:     c.GetUint("userId"),
		Name:       req.Name,
		Sex:        req.Sex,
		Title:      req.Title,
		StartTime:  req.StartTime,
		EndTime:    req.EndTime,
		LiveStatus: 1,
		Image:      req.Image,
	}
	err = glodal.DB.Create(&live).Error
	if live.Image != "png" && live.Image != "jpg" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "图片上传失败",
			"data": nil,
		})
		return
	}
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "直播间添加失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "直播间添加成功",
		"data": live,
	})
}

func LiveUpdate(c *gin.Context) {
	var req request.LiveUpdate
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var lives model.Live
	err = glodal.DB.Where("live_id = ?", req.LiveId).Find(&lives).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "该直播间不存在",
			"data": nil,
		})
		return
	}
	live := model.Live{
		LiveId:     lives.ID,
		StartTime:  req.StartTime,
		EndTime:    req.EndTime,
		LiveStatus: 2,
	}
	err = glodal.DB.Updates(&live).Error
	if live.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "直播数据修改失败",
			"data": live,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "直播数据修改成功",
		"data": live,
	})
}

func LiveList(c *gin.Context) {
	var list []model.Live
	err := glodal.DB.Find(&list).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "查看失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查看成功",
		"data": list,
	})
}
